package com.yihu.wlyy.service.app.sign;

import java.util.*;

import com.yihu.wlyy.entity.*;
import com.yihu.wlyy.entity.address.Hospital;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.entity.doctor.DoctorService;
import com.yihu.wlyy.entity.doctor.DoctorTeam;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientDisease;
import com.yihu.wlyy.repository.*;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.NumberUtils;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.IdcardInfoExtractor;
import com.yihu.wlyy.util.MessageType;

/**
 * 家庭签约业务处理类
 *
 * @author George
 */
@Component
@Transactional
public class FamilyContractService extends BaseService {

    @Autowired
    private DoctorPatientDao doctorPatientDao;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorServiceDao doctorServiceDao;
    @Autowired
    private HospitalDao hospitalDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private DoctorTeamDao doctorTeamDao;
    @Autowired
    private DrHealthTeamMemberDao doctorTeamDoctor;
    @Autowired
    private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
    @Autowired
    private ConsultTeamDao consultTeamDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WlyySignFamilyCodeDao wlyySignFamilyCodeDao;
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private PatientDiseaseService patientDiseaseService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PatientDiseaseDao patientDiseaseDao;
    @Autowired
    private SbInfoDao sbInfoDao;

    public SignFamily findByPatientByType(String patient, int type) {
        return signFamilyDao.findByPatientAndType(patient, type);
    }

    public SignFamily findByPatient(String patient) {
        return signFamilyDao.findByjiatingPatient(patient);
    }

    public SignFamily findSignByPatient(String patient) {
        return signFamilyDao.findSignByPatient(patient);
    }

    /**
     * 获取患者待签约数据
     *
     * @param patient
     * @return
     */
    public SignFamily findSigningByPatient(String patient){
        return signFamilyDao.findSigningByPatient(patient);
    }

    /**
     * 查询医院列表
     *
     * @param type     医院类型：0全部，1大医院，2社区医院
     * @param province 省代码
     * @param city     城市代码
     * @param key      搜索关键字
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<Hospital> findHospitals(int type, String province, String city, String town, String key, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.ASC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (type == 1) {
            // 查询大医院
            filters.put("level", new SearchFilter("level", Operator.EQ, 1));
        } else if (type == 2) {
            // 查询社区医院
            filters.put("level", new SearchFilter("level", Operator.EQ, 2));
        }
        if (StringUtils.isNotEmpty(province)) {
            filters.put("province", new SearchFilter("province", Operator.EQ, province));
        }
        if (StringUtils.isNotEmpty(city)) {
            filters.put("city", new SearchFilter("city", Operator.EQ, city));
        }
        if (StringUtils.isNotEmpty(town)) {
            filters.put("town", new SearchFilter("town", Operator.EQ, town));
        }
        if (StringUtils.isNotEmpty(key)) {
            filters.put("name", new SearchFilter("name", Operator.LIKE, key));
        }
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.GT, id));
        }
        // 未作废
        filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
        Specification<Hospital> spec = DynamicSpecifications.bySearchFilter(filters.values(), Hospital.class);
        return hospitalDao.findAll(spec, pageRequest);
    }

    /**
     * 查询医院下的医生
     *
     * @param hospital
     * @param level    医生类型：1专科医生，2全科医生，3健康管理师
     * @return
     */
    public Page<Doctor> findDoctors(String hospital, int level, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.ASC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        if (StringUtils.isNoneEmpty(hospital)) {
            filters.put("hospital", new SearchFilter("hospital", Operator.EQ, hospital));
        }
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.GT, id));
        }
        // 医生类型过滤
        if (level > 0) {
            filters.put("level", new SearchFilter("level", Operator.EQ, level));
        }
        // 未作废
        filters.put("status", new SearchFilter("status", Operator.EQ, 1));
        Specification<Doctor> spec = DynamicSpecifications.bySearchFilter(filters.values(), Doctor.class);
        return doctorDao.findAll(spec, pageRequest);
    }

    /**
     * 查询医生主页信息
     *
     * @param doctor  医生标识
     * @param patient 患者标识
     * @return
     */
    public JSONObject findDoctorMainPage(String patient, String doctor) {
        JSONObject json = new JSONObject();
        // 查询医生基本信息
        Doctor d = doctorDao.findByCode(doctor);
        json.put("doctor", d.getCode());
        json.put("name", d.getName());
        json.put("photo", d.getPhoto());
        json.put("sex",d.getSex());
        json.put("job", d.getJob());
        json.put("jobName", d.getJobName());
        json.put("hospital", d.getHosptialName());
        json.put("dept", d.getDeptName());
        json.put("intro", d.getIntroduce());
        json.put("expertise", d.getExpertise());
        // 查询与当前医生的签约状态
        SignFamily sf = signFamilyDao.findByDoctorPatient(doctor, patient);
        if (sf == null) {
            // 没有签约信息
            json.put("sign", -1);
        } else {
            // 有签约信息
            json.put("sign", sf.getStatus());
        }
        //设置查看病人所在分组
        List<DoctorPatientGroupInfo> dctorPatientGroupInfo = doctorPatientGroupInfoDao.findByMorenPatient(patient);
        if (dctorPatientGroupInfo != null && dctorPatientGroupInfo.size() > 0) {
            json.put("group", dctorPatientGroupInfo.get(0).getGroup());
        } else {
            json.put("group", "0");
        }
        // 查询医生服务
        List<DoctorService> list = doctorServiceDao.findByDoctor(doctor);
        JSONArray services = new JSONArray();
        for (DoctorService ds : list) {
            if (ds == null) {
                continue;
            }
            JSONObject service = new JSONObject();
            service.put("logo", ds.getLogo());
            service.put("title", ds.getTitle());
            service.put("content", ds.getContent());
            service.put("url", ds.getUrl());
            services.put(service);
        }
        json.put("services", services);
        return json;
    }

    /**
     * 查询患者与医生的签约信息
     *
     * @param patient
     * @param doctor
     * @return
     */
    public int findSignStatus(String patient, String doctor) {
        // 查询与当前医生的签约状态
        SignFamily sf = signFamilyDao.findByDoctorPatient(doctor, patient);
        if (sf == null) {
            // 没有签约信息
            return -1;
        } else {
            // 有签约信息
            return sf.getStatus();
        }
    }

    /**
     * 校验签约状态
     *
     * @return
     * @throws Exception
     */
    public JSONObject checkSign(Patient patient) throws Exception {
        JSONObject json = new JSONObject();
        // 查询是否已存在家庭签约
        SignFamily sf = signFamilyDao.findByIdcard(patient.getIdcard());
        if (sf != null) {
            // 已签约
            json.put("sign", 1);
        } else {
            // 未签约
            json.put("sign", 0);
        }
        return json;
    }

    /**
     * 校验当前openid是否签约家庭医生
     *
     * @return
     */
    public String checkPatient(String patient) {
        SignFamily sf = signFamilyDao.findByjiatingPatientStatus0(patient);
        if (sf != null) {
            return sf.getDoctor();
        }
        return null;
    }

    /**
     * 查询是否存在签约状态
     *
     * @param idcard
     * @return
     */
    public int hasSingStatus(String idcard) {
        return signFamilyDao.hasSingStatus(idcard);
    }

    /**
     * 发起签约申请
     *
     * @param province     省代码
     * @param provinceName 省名称
     * @param city         城市代码
     * @param cityName     城市名称
     * @param town         区县代码
     * @param townName     区县名称
     * @param address      详细地址
     * @param name         患者姓名
     * @param doctor       医生标识
     * @param openid       微信openid
     * @param patient      患者标识
     * @param idcard       患者身份证号
     * @param ssc          患者社保卡号
     * @param mobile       患者手机号
     * @param emerMobile   患者紧急联系人
     * @return
     */
    public JSONObject sign(String province,
                           String provinceName,
                           String city,
                           String cityName,
                           String town,
                           String townName,
                           String address,
                           String name,
                           String doctor,
                           String openid,
                           String patient,
                           String idcard,
                           String ssc,
                           String mobile,
                           String emerMobile) {
        // 查询三师签约
        JSONObject json = new JSONObject();
        SignFamily sc = signFamilyDao.findByIdcard(idcard);
        //判断身份证号是否已经注册
        if (sc != null) {
            json.put("res", "-3");
            return json;
        }
        Doctor d = doctorDao.findByCode(doctor);
        SignFamily sf = new SignFamily();
        sf.setCode(getCode());
        // 设置两网编码
        sf.setLwCode(sc != null ? sc.getCode() : null);
        sf.setCzrq(new Date());
        sf.setPatientApplyDate(new Date());
        sf.setDoctor(doctor);
        sf.setMobile(mobile);
        sf.setDoctorName(d.getName());
        sf.setEmerMobile(emerMobile);
        sf.setName(name);
        sf.setIdcard(idcard);
        sf.setOpenid(openid);
        sf.setPatient(patient);
        sf.setHospital(d.getHospital());
        sf.setHospitalName(d.getHosptialName());
        sf.setSsc(ssc);
        sf.setStatus(0);//0为初始状态
        sf.setType(2);// 设置为家庭签约
        sf.setSignType("1");//用户申请
        sf.setSignSource("2");//签约来源【1 社区签约 2 移动签约】
        //******************扣费接口**********************/
        sf.setExpensesStatus("0");   //扣费状态 【0未扣费 1已扣费 2已退费】
        // 判断用户表是否存在该身份证号
        Patient p = patientDao.findByIdcard(idcard);
        if (p == null) {
            // 插入患者基本信息
            IdcardInfoExtractor ie = new IdcardInfoExtractor(idcard);
            p = new Patient();
            p.setCode(getCode());
            p.setName(name);
            p.setProvince(province);
            p.setProvinceName(provinceName);
            p.setCity(city);
            p.setCityName(cityName);
            p.setTown(town);
            p.setTownName(townName);
            p.setAddress(address);
            p.setOpenid(openid);
            p.setIdcard(idcard);
            p.setMobile(mobile);
            p.setSsc(ssc);
            // 从身份证号中提取生日
            p.setBirthday(ie.getBirthday());
            // 从身份证号中提取性别
            p.setSex(ie.getGender());
            p.setCzrq(new Date());
            p.setStatus(1);
            // 保存新的用户信息
            p = patientDao.save(p);
        } else {
            if (StringUtils.isNotEmpty(patient) && !StringUtils.equals(p.getCode(), patient)) {
                // 身份证信息与登录信息不匹配
                json.put("res", -1);
                return json;
            }
            if (StringUtils.isNotEmpty(openid) && !StringUtils.equals(p.getOpenid(), openid)) {
                // 身份证信息与登录信息不匹配
                json.put("res", -1);
                return json;
            }
            if (StringUtils.isNotEmpty(idcard) && !StringUtils.equals(p.getIdcard(), idcard)) {
                // 身份证信息与登录信息不匹配
                json.put("res", -1);
                return json;
            }
        }
        // 更新签约用户信息
        patient = p.getCode();
        sf.setPatient(patient);
        SignFamily temp = signFamilyDao.save(sf);
        if (temp != null) {
            // 添加签约消息
            Message message = new Message();
            message.setCzrq(new Date());
            message.setContent("您有一条新的家庭签约申请！");
            message.setRead(1);//设置未读
            message.setReceiver(doctor);//设置接受医生的code
            message.setSender(patient);//设置发送的用户
            message.setSenderName(p.getName());
            message.setCode(getCode());
            message.setSenderPhoto(p.getPhoto());
            message.setTitle("家庭签约申请");
            message.setType(1);//家庭签约信息
            message.setReadonly(1);//是否只读消息
            message.setSignStatus("1");//新的签约
            message.setSex(p.getSex());
            message.setOver("1");//未处理
            messageDao.save(message);
            // 发送消息给医生
            PushMsgTask.getInstance().put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_NEW_SIGN_WEB.D_SW_01.name(), MessageType.MESSAGE_TYPE_DOCTOR_NEW_SIGN_WEB.家庭签约.name(), "您有一条新的家庭签约申请！", patient);
        }
        json.put("id", p.getId());
        json.put("uid", p.getCode());
        json.put("res", 1);
        return json;
    }

    /**
     * 取消签约申请
     *
     * @param patient 患者标识
     * @param doctor  医生标识
     * @return
     */
    public int unsign(String patient, String doctor) {
        //修改签约标识为无效
        SignFamily sf = signFamilyDao.findByDoctorPatient(doctor, patient);
        Message message = messageDao.findByPatient(patient, doctor);
        if (sf.getStatus() != 0 && sf.getStatus() != 2) {
            return -2;
        }
        if (sf != null) {
            sf.setStatus(-1);
        } else {
            return -2;
        }
        //修改信息为无效
        if (message != null) {
            message.setRead(0);
            message.setOver("0");
        }
        return 200;
    }

    /**
     * 申请解约
     *
     * @param patient 患者标识
     * @param doctor  医生标识
     * @param openid  微信openid
     * @param reason  解约理由
     * @return
     */
    public int surrender(String patient, String patientName, String userPhoto, String doctor, String doctorName, String openid, String reason, int sex) {
        // 更新为待解约
        int res = signFamilyDao.surrender(patient, doctor);
        SignFamily signFamily=  signFamilyDao.findByjiatingPatient(patient);
        signFamily.setPatientApplyUnsignDate(new Date());
        if (res == 0) {
            return 0;
        }
        // 添加签约消息
        Message message = new Message();
        // 消息时间
        message.setCzrq(new Date());
        // 消息内容
        message.setContent("[" + patientName + "]申请解除与您的签约关系");
        // 未读
        message.setRead(1);
        message.setReceiverName(doctorName);
        // 接收人
        message.setReceiver(doctor);
        message.setCode(getCode());
        // 发送人
        message.setSender(patient);
        message.setSenderName(patientName);
        message.setSenderPhoto(userPhoto);
        // 标题
        message.setTitle("解除家庭签约申请");
        message.setType(1);
        message.setSignStatus("4");
        message.setReadonly(1);
        message.setSex(sex);
        message.setOver("1");
        // 设置解约理由
        message.setReason(reason);
        messageDao.save(message);
        // 发送消息给医生
        PushMsgTask.getInstance().put(doctor, MessageType.MESSAGE_TYPE_DOCTOR_SIGN_WEB_RELIEVE.D_SW_02.name(), MessageType.MESSAGE_TYPE_DOCTOR_SIGN_WEB_RELIEVE.家庭签约.name(), patientName + " 申请解除与您的家庭签约！", patient);
        return 1;
    }

    /**
     * 查询患者的签约消息
     *
     * @param id
     * @param pagesize
     * @return
     */
    public Page<Message> findMessageByPatient(String patient, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("receiver", new SearchFilter("receiver", Operator.EQ, patient));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
    }

    /**
     * 查询跟医生相关的家庭签约信息
     *
     * @param type     0全部，1待签约，2已签约，3待解约，4已解约
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<SignFamily> findSignByDoctor(int type, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        // 只查家庭签约（网络签约）
        filters.put("type", new SearchFilter("type", Operator.EQ, 2));
        switch (type) {
            case 1:
                // 待签约
                filters.put("status", new SearchFilter("status", Operator.EQ, 0));
                break;
            case 2:
                // 已签约
                filters.put("status", new SearchFilter("status", Operator.EQ, 1));
                break;
            case 3:
                // 待解约
                filters.put("status", new SearchFilter("status", Operator.EQ, 2));
                break;
            case 4:
                // 已解约
                filters.put("status", new SearchFilter("status", Operator.EQ, -3));
                break;
        }
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        Specification<SignFamily> spec = DynamicSpecifications.bySearchFilter(filters.values(), SignFamily.class);
        return signFamilyDao.findAll(spec, pageRequest);
    }

    /**
     * 代理签约
     *
     * @param name             患者姓名
     * @param doctor           医生标识
     * @param doctorName       医生姓名
     * @param doctorHealth     健康管理师标识
     * @param doctorHealthName 健康管理师姓名
     * @param hospital         签约医院标识
     * @param hospitalName     签约医院名称
     * @param idcard           患者身份证号
     * @param ssc              患者社保卡号
     * @param mobile           患者手机号
     * @param emerMobile       患者紧急联系人
     * @param expenses
     * @return
     * @throws Exception
     */
    synchronized public SignFamily agent(String access_token, String name,
                                         String doctor, String doctorName,
                                         String doctorHealth, String doctorHealthName,
                                         String majorDoctor,
                                         String majorDoctorName,
                                         String hospital, String hospitalName,
                                         String idcard, String ssc, String mobile,
                                         String emerMobile, String images, String disease, String expenses, String signDoctorCode,
                                         String signDoctorName, String signDoctorLevel,String customGroup) throws Exception {
        // 查询是否有家庭签约
        SignFamily sc = signFamilyDao.findByIdcard(idcard);
        if (sc != null) {
            throw new Exception("已签约了家庭医生！");
        }
        //判断是否有三师签约 并且判断全科医生一致
        SignFamily sssignFamily = signFamilyDao.findSSByIdcard(idcard);
        if (sssignFamily != null&&!doctor.equals(sssignFamily.getDoctor())) {
            throw new Exception("全科医生不一致！");
        }

        List<SystemDict> systemDicts=  systemDictDao.findByDictName("SIGN_YEAR");
        String signYear=systemDicts.get(0).getCode();

        SignFamily sf = new SignFamily();
        sf.setSignYear(signYear);//设置签约年度
        sf.setBegin(DateUtil.getNowDateShort());
        sf.setCode(getCode());
        sf.setCzrq(new Date());
        sf.setDoctor(doctor);
        sf.setDoctorName(doctorName);
        sf.setDoctorHealth(doctorHealth);
        sf.setExpensesType(expenses);
        sf.setFamilyCode(createSignCode(doctor, hospital));
        sf.setDoctorHealthName(doctorHealthName);
        sf.setEmerMobile(emerMobile);
        sf.setEnd(DateUtil.strToDateShort(DateUtil.getNextYear(DateUtil.getNowDateShort(), 1)));
        sf.setName(name);
        sf.setIdcard(idcard);
        sf.setMobile(mobile);
        sf.setHospital(hospital);
        sf.setHospitalName(hospitalName);
        String sscD="";
        if(StringUtils.isNumeric(ssc.trim())){
            //如果是纯数字的医保号换成D开头的
            sscD=sbInfoDao.findBySfzh18Max(idcard).getCardno();
        }else{
            sscD=ssc;
        }
        sf.setSsc(sscD);
        sf.setStatus(1);// 代理签约，直接生效
        sf.setImages(images);
        sf.setApplyDate(new Date());
        sf.setType(2);// 设置为家庭签约
        sf.setSignType("2");//手工带签
        sf.setSignDoctorCode(doctor);
        sf.setSignDoctorLevel("2");
        sf.setSignDoctorName(doctorName);
        sf.setAgentDoctorCode(signDoctorCode);
        sf.setAgentDoctorLevel(signDoctorLevel);
        sf.setAgentDoctorName(signDoctorName);
        sf.setSignSource("2");//签约来源【1 社区签约 2 移动签约】
        //******************扣费接口**********************/
        sf.setExpensesStatus("0");   //扣费状态 【0未扣费 1已扣费 2已退费】
        // 查询该患者是否已注册
        Patient patient = patientDao.findByIdcard(idcard);
        if (patient == null) {
            // 插入患者基本信息
            IdcardInfoExtractor ie = new IdcardInfoExtractor(idcard);
            patient = new Patient();
            patient.setCode(getCode());
            patient.setName(name);
            patient.setIdcard(idcard);
            patient.setSsc(sscD);
            patient.setBirthday(ie.getBirthday());
            patient.setSex(ie.getGender());
            patient.setMobile(mobile);
            patient.setStatus(1);
            patient.setDisease(0);
        }
        //病人疾病更新
//        if (!StringUtils.isEmpty(disease)) {
//            patient.setDisease(Integer.valueOf(disease));
//        }
        // 保存用户信息
        patientDao.save(patient);

        sf.setOpenid(patient.getOpenid());
        sf.setPatient(patient.getCode());
        // 改为签约生效
        sf.setStatus(1);
        // 更新签约日期
        sf.setBegin(DateUtil.getNowDateShort());
        sf.setEnd(DateUtil.strToDateShort(DateUtil.getNextYear(DateUtil.getNowDateShort(), 1)));
        //建立团队
        DoctorTeam doctorTeam = new DoctorTeam();
        String doctorTeamCode = getCode();
        doctorTeam.setCode(doctorTeamCode);
        doctorTeam.setCzrq(new Date());
        doctorTeam.setName("团队名称:" + name);
        doctorTeam.setSignType("2");//家庭签约
        doctorTeam.setDel("1");
        doctorTeamDao.save(doctorTeam);
        sf.setTeamCode(doctorTeamCode);
        signFamilyDao.save(sf);
        //添加团队成员
        //添加健康管理师
        DrHealthTeamMember wlyyDoctorTeamDoctor = new DrHealthTeamMember();
        wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
        wlyyDoctorTeamDoctor.setMemberCode(doctorHealth);
        wlyyDoctorTeamDoctor.setName(doctorHealthName);
        wlyyDoctorTeamDoctor.setDel("1");
        wlyyDoctorTeamDoctor.setType(3);
        wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
        wlyyDoctorTeamDoctor.setCode(getCode());
        wlyyDoctorTeamDoctor.setCzrq(new Date());
        doctorTeamDoctor.save(wlyyDoctorTeamDoctor);
        //添加全科医生
        wlyyDoctorTeamDoctor = new DrHealthTeamMember();
        wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
        wlyyDoctorTeamDoctor.setMemberCode(doctor);
        wlyyDoctorTeamDoctor.setName(doctorName);
        wlyyDoctorTeamDoctor.setDel("1");
        wlyyDoctorTeamDoctor.setType(2);
        wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
        wlyyDoctorTeamDoctor.setCode(getCode());
        wlyyDoctorTeamDoctor.setCzrq(new Date());
        doctorTeamDoctor.save(wlyyDoctorTeamDoctor);

//        if (StringUtils.isNotEmpty(disease) && !disease.equals("0")) {
//            //如果有选择病种
//            //添加专科医生
//            wlyyDoctorTeamDoctor = new DrHealthTeamMember();
//            wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
//            wlyyDoctorTeamDoctor.setMemberCode(majorDoctor);
//            wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
//            wlyyDoctorTeamDoctor.setName(majorDoctorName);
//            wlyyDoctorTeamDoctor.setDel("1");
//            wlyyDoctorTeamDoctor.setType(1);
//            wlyyDoctorTeamDoctor.setCode(getCode());
//            wlyyDoctorTeamDoctor.setCzrq(new Date());
//
//            doctorTeamDoctor.save(wlyyDoctorTeamDoctor);
//        }

        //添加患者和团队的关系
        DrHealthTeamMember wlyyDoctorTeamPatient = new DrHealthTeamMember();
        wlyyDoctorTeamPatient.setTeam(doctorTeamCode);
        wlyyDoctorTeamPatient.setMemberCode(patient.getCode());
        wlyyDoctorTeamPatient.setName(patient.getName());
        wlyyDoctorTeamPatient.setDel("1");
        wlyyDoctorTeamPatient.setSignType("2");//家庭签约
        wlyyDoctorTeamPatient.setType(5);
        wlyyDoctorTeamPatient.setCode(getCode());
        wlyyDoctorTeamPatient.setCzrq(new Date());
        doctorTeamDoctor.save(wlyyDoctorTeamPatient);

        //病人分组类别
        String groupCode = "1";
        //判断病人分组
        if (!StringUtils.isEmpty(disease)) {
            List<String> diseases = Arrays.asList(disease.split(","));
            if(diseases.contains("1") || diseases.contains("2")) {
                groupCode = "2";
            }
        } else {
            String birth = patient.getIdcard().substring(6, 14);
            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(4, 6));
            int day = Integer.valueOf(birth.substring(6));
            Calendar cal = Calendar.getInstance();
            int age = cal.get(Calendar.YEAR) - year;
            //周岁计算
            if (cal.get(Calendar.MONTH) > (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) > day)) {
                age--;
            }
            if (age >= 65) {
                groupCode = "3";
            }
        }

        //把病人添加到健康管理师的健康分组里
        DoctorPatientGroupInfo doctorPatientGroupInfo = new DoctorPatientGroupInfo();
        doctorPatientGroupInfo.setCzrq(new Date());
        doctorPatientGroupInfo.setDoctor(doctorHealth);
        doctorPatientGroupInfo.setStatus(1);
        doctorPatientGroupInfo.setPatient(patient.getCode());
        doctorPatientGroupInfo.setPname(patient.getName());
        doctorPatientGroupInfo.setPartAmount(0);
        doctorPatientGroupInfo.setGroup(groupCode);//默认健康分组
        doctorPatientGroupInfo.setQyrq(new Date());
        doctorPatientGroupInfo.setSignType("2");//家庭签约
        doctorPatientGroupInfoDao.save(doctorPatientGroupInfo);

        //把病人添加到全科医生的健康分组里
        doctorPatientGroupInfo = new DoctorPatientGroupInfo();
        doctorPatientGroupInfo.setCzrq(new Date());
        doctorPatientGroupInfo.setDoctor(doctor);
        doctorPatientGroupInfo.setStatus(1);
        doctorPatientGroupInfo.setPatient(patient.getCode());
        doctorPatientGroupInfo.setPname(patient.getName());
        doctorPatientGroupInfo.setPartAmount(0);
        doctorPatientGroupInfo.setGroup(groupCode);//默认健康分组
        doctorPatientGroupInfo.setQyrq(new Date());
        doctorPatientGroupInfo.setSignType("2");//家庭签约
        doctorPatientGroupInfoDao.save(doctorPatientGroupInfo);

        if(!StringUtils.isEmpty(customGroup) && !customGroup.equals("0")){
            DoctorPatientGroupInfo customDoctorGroup = new DoctorPatientGroupInfo();

            customDoctorGroup.setCzrq(new Date());
            customDoctorGroup.setDoctor(signDoctorCode);
            customDoctorGroup.setStatus(1);
            customDoctorGroup.setPatient(patient.getCode());
            customDoctorGroup.setPname(patient.getName());
            customDoctorGroup.setPartAmount(0);
            customDoctorGroup.setGroup(customGroup);
            customDoctorGroup.setQyrq(new Date());
            customDoctorGroup.setSignType("2");//家庭签约

            doctorPatientGroupInfoDao.save(customDoctorGroup);

            SignFamily signFamily = signFamilyDao.findSsSignByDoctorPatient(sf.getDoctor(),sf.getPatient());

            if(signFamily != null){
                DoctorPatientGroupInfo ssDoctorGroup = new DoctorPatientGroupInfo();

                ssDoctorGroup.setCzrq(new Date());
                ssDoctorGroup.setDoctor(signDoctorCode);
                ssDoctorGroup.setStatus(1);
                ssDoctorGroup.setPatient(patient.getCode());
                ssDoctorGroup.setPname(patient.getName());
                ssDoctorGroup.setPartAmount(0);
                ssDoctorGroup.setGroup(customGroup);
                ssDoctorGroup.setQyrq(new Date());
                ssDoctorGroup.setSignType("1");//三师签约

                doctorPatientGroupInfoDao.save(ssDoctorGroup);
            }
        }

        List<DoctorPatientGroupInfo> groups = doctorPatientGroupInfoDao.findPatientGroups(patient.getCode());

        if (groups != null && groups.size() > 0) {
            for (DoctorPatientGroupInfo group : groups) {
                if(StringUtils.isNotEmpty(group.getSignType()) && group.getSignType().equals("2")) {
                    continue;
                }
                if(group.getGroup().equals(customGroup)){
                    continue;
                }

                DoctorPatientGroupInfo patientGroup = new DoctorPatientGroupInfo();

                patientGroup.setCzrq(new Date());
                patientGroup.setDoctor(group.getDoctor());
                patientGroup.setStatus(1);
                patientGroup.setPatient(patient.getCode());
                patientGroup.setPname(patient.getName());
                patientGroup.setPartAmount(0);
                patientGroup.setGroup(group.getGroup());
                patientGroup.setQyrq(new Date());
                patientGroup.setSignType("2");//家庭签约

                doctorPatientGroupInfoDao.save(patientGroup);
            }
        }

        if(!StringUtils.isEmpty(disease) && !disease.equals("0")){
            boolean flag =  patientDiseaseService.updatePatientDisease(sf.getPatient(),disease);

            if(!flag){
                throw new Exception("疾病更新失败");
            }
        }

        SignFamily temp = signFamilyDao.save(sf);
        if (temp != null && patient != null) {
            Doctor doc = doctorDao.findByCode(sf.getDoctor());
            Hospital hos = hospitalDao.findByCode(doc.getHospital());

            String content= "祝贺您，成功签约" + sf.getDoctorName() + "医生团队，您已可以享受家庭医生所带来的无微不至的健康保健服务。"+
                    "为了给您提供更好的服务，请尽快到" + (hos != null ? hos.getName() : "") + "社区（地址：" +
                    (hos != null ? hos.getAddress() : "") + "）缴费。";
            JSONObject json = new JSONObject();
            json.put("first", "签约成功通知");
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("date", DateUtil.dateToStrShort(sf.getBegin()));
            json.put("content", content);
            json.put("remark", "您好，您成功签约家庭医生");
            // 添加到发送队列
            PushMsgTask.getInstance().putWxMsg(access_token, 1, sf.getOpenid(), sf.getName(), json);
        }
        return temp;
    }
    /**
     * 处理签约申请
     *
     * @param healthDoctor     健康管理师标识
     * @param healthDoctorName 健康管理师姓名
     * @param msgid            消息id
     * @param patientCard      患者身份证
     * @param type             处理类型：1同意，2拒绝
     * @return
     */

    public int handleSign(String signType,
                          String access_token,
                          String healthDoctor,
                          String healthDoctorName,
                          long msgid,
                          String patientCard, int type, String disease, String majorDoctor, String majorhDoctorName,String customGroup, String expenses) throws Exception {
        if (type != 1 && type != 2) {
            return -1;
        }

        // 查询患者信息
        Patient p = patientDao.findByIdcard(patientCard);

        // 更新消息状态为已处理
        if (msgid > 0) {
            Message message = messageDao.findOne(msgid);
            message.setRead(0);//设置已读
            message.setOver("0");//设置消息操作结束
            message.setCzrq(new Date());
        }
        // 判断患者有没有家庭签约
        SignFamily sf = signFamilyDao.findByPatientStatus(patientCard, 0);
        if (sf == null) {
            return 0;
        }
        if (type == 1) {
            List<SystemDict> systemDicts=  systemDictDao.findByDictName("SIGN_YEAR");
            String year=systemDicts.get(0).getCode();
            //病人疾病更新
//            if (!StringUtils.isEmpty(disease)) {
//                p.setDisease(Integer.valueOf(disease));
//            }

            //签约类型：1三师签约，2家庭签约
            // 改为签约生效
            sf.setStatus(1);
            // 更新签约日期
            sf.setBegin(DateUtil.getNowDateShort());
            sf.setSignType("1");//患者发起签约
            sf.setExpensesType(expenses);//收费类别
            sf.setEnd(DateUtil.strToDateShort(DateUtil.getNextYear(DateUtil.getNowDateShort(), 1)));
            //设置签约人  患者发起的签约 默认签约人是全科医生
            sf.setSignDoctorCode(sf.getDoctor());
            sf.setSignDoctorName(sf.getDoctorName());
            sf.setSignDoctorLevel("2");
            // 更新健康管理师
            sf.setDoctorHealth(healthDoctor);
            sf.setDoctorHealthName(healthDoctorName);
            sf.setCzrq(new Date());
            sf.setSignYear(year);//设置签约年度
            sf.setApplyDate(new Date());
            Doctor doctor = doctorDao.findByCode(sf.getDoctor());
            sf.setFamilyCode(createSignCode(sf.getDoctor(), doctor.getHospital()));
            //建立团队
            DoctorTeam doctorTeam = new DoctorTeam();
            String doctorTeamCode = getCode();
            doctorTeam.setName("三师签约团队患者:" + p.getName());
            doctorTeam.setCode(doctorTeamCode);
            doctorTeam.setCzrq(new Date());
            doctorTeam.setSignType("2");
            doctorTeam.setDel("1");
            doctorTeamDao.save(doctorTeam);
            sf.setTeamCode(doctorTeamCode);
            //添加团队成员
            //添加健康管理师
            DrHealthTeamMember wlyyDoctorTeamDoctor = new DrHealthTeamMember();
            wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
            wlyyDoctorTeamDoctor.setMemberCode(healthDoctor);
            wlyyDoctorTeamDoctor.setName(healthDoctorName);
            wlyyDoctorTeamDoctor.setDel("1");

            wlyyDoctorTeamDoctor.setSignType("2");
            wlyyDoctorTeamDoctor.setType(3);
            wlyyDoctorTeamDoctor.setCode(getCode());
            wlyyDoctorTeamDoctor.setCzrq(new Date());
            doctorTeamDoctor.save(wlyyDoctorTeamDoctor);
            //添加全科医生
            wlyyDoctorTeamDoctor = new DrHealthTeamMember();
            wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
            wlyyDoctorTeamDoctor.setMemberCode(sf.getDoctor());
            wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
            wlyyDoctorTeamDoctor.setName(sf.getDoctorName());
            wlyyDoctorTeamDoctor.setDel("1");
            wlyyDoctorTeamDoctor.setType(2);
            wlyyDoctorTeamDoctor.setCode(getCode());
            wlyyDoctorTeamDoctor.setCzrq(new Date());
            doctorTeamDoctor.save(wlyyDoctorTeamDoctor);
            //添加患者和团队的关系
            DrHealthTeamMember wlyyDoctorTeamPatient = new DrHealthTeamMember();
            wlyyDoctorTeamPatient.setTeam(doctorTeamCode);
            wlyyDoctorTeamPatient.setMemberCode(sf.getPatient());
            wlyyDoctorTeamPatient.setName(p.getName());
            wlyyDoctorTeamPatient.setDel("1");
            wlyyDoctorTeamPatient.setSignType("2");//家庭签约
            wlyyDoctorTeamPatient.setType(5);//患者
            wlyyDoctorTeamPatient.setCode(getCode());
            wlyyDoctorTeamPatient.setCzrq(new Date());
            doctorTeamDoctor.save(wlyyDoctorTeamPatient);

//            if (StringUtils.isNotEmpty(disease) && !disease.equals("0")) {
//                //如果有选择病种
//                //添加专科医生
//                wlyyDoctorTeamDoctor = new DrHealthTeamMember();
//                wlyyDoctorTeamDoctor.setTeam(doctorTeamCode);
//                wlyyDoctorTeamDoctor.setMemberCode(majorDoctor);
//                wlyyDoctorTeamDoctor.setSignType("2");//家庭签约
//                wlyyDoctorTeamDoctor.setName(majorhDoctorName);
//                wlyyDoctorTeamDoctor.setDel("1");
//                wlyyDoctorTeamDoctor.setType(1);
//                wlyyDoctorTeamDoctor.setCode(getCode());
//                wlyyDoctorTeamDoctor.setCzrq(new Date());
//                doctorTeamDoctor.save(wlyyDoctorTeamDoctor);
//            }
        } else {
            // 医生拒绝
            sf.setStatus(-2);
            // 拒绝签约
            JSONObject json = new JSONObject();
            json.put("first", "签约失败通知");
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("date", DateUtil.dateToStrShort(new Date()));
            json.put("content", "您与 " + sf.getDoctorName() + " 医生建立家庭医生签约关系失败，请查看！");
            json.put("remark", "您好，签约家庭医生失败通知");
            // 添加到发送队列
            PushMsgTask.getInstance().putWxMsg(access_token, 2, sf.getOpenid(), sf.getName(), json);
            return 2;
        }

        //病人分组类别
        String groupCode = "1";
        //判断病人分组
        if (!StringUtils.isEmpty(disease)) {
            List<String> diseases = Arrays.asList(disease.split(","));
            if(diseases.contains("1") || diseases.contains("2")) {
                groupCode = "2";
            }
        } else {
            String birth = p.getIdcard().substring(6, 14);
            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(4, 6));
            int day = Integer.valueOf(birth.substring(6));
            Calendar cal = Calendar.getInstance();
            int age = cal.get(Calendar.YEAR) - year;
            //周岁计算
            if (cal.get(Calendar.MONTH) > (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) > day)) {
                age--;
            }
            if (age >= 65) {
                groupCode = "3";
            }
        }

        //设置签约人到全科管理师和健康管理师的健康人群分组里
        //给病人分组
        //把病人添加到健康管理师的健康分组里
        DoctorPatientGroupInfo doctorPatientGroupInfo = new DoctorPatientGroupInfo();
        doctorPatientGroupInfo.setCzrq(new Date());
        doctorPatientGroupInfo.setDoctor(healthDoctor);
        doctorPatientGroupInfo.setStatus(1);
        doctorPatientGroupInfo.setPatient(p.getCode());
        doctorPatientGroupInfo.setPname(p.getName());
        doctorPatientGroupInfo.setPartAmount(0);
        doctorPatientGroupInfo.setGroup(groupCode);//默认健康分组
        doctorPatientGroupInfo.setQyrq(new Date());
        doctorPatientGroupInfo.setSignType("2");//家庭签约
        doctorPatientGroupInfoDao.save(doctorPatientGroupInfo);

        //把病人添加到全科医生的健康分组里
        doctorPatientGroupInfo = new DoctorPatientGroupInfo();
        doctorPatientGroupInfo.setCzrq(new Date());
        doctorPatientGroupInfo.setDoctor(sf.getDoctor());
        doctorPatientGroupInfo.setStatus(1);
        doctorPatientGroupInfo.setPatient(p.getCode());
        doctorPatientGroupInfo.setPname(p.getName());
        doctorPatientGroupInfo.setPartAmount(0);
        doctorPatientGroupInfo.setGroup(groupCode);//默认健康分组
        doctorPatientGroupInfo.setQyrq(new Date());
        doctorPatientGroupInfo.setSignType("2");//家庭签约
        doctorPatientGroupInfoDao.save(doctorPatientGroupInfo);

        if(!StringUtils.isEmpty(customGroup) && !customGroup.equals("0")){
            DoctorPatientGroupInfo customDoctorGroup = new DoctorPatientGroupInfo();

            customDoctorGroup.setCzrq(new Date());
            customDoctorGroup.setDoctor(sf.getDoctor());
            customDoctorGroup.setStatus(1);
            customDoctorGroup.setPatient(p.getCode());
            customDoctorGroup.setPname(p.getName());
            customDoctorGroup.setPartAmount(0);
            customDoctorGroup.setGroup(customGroup);
            customDoctorGroup.setQyrq(new Date());
            customDoctorGroup.setSignType("2");//家庭签约
            doctorPatientGroupInfoDao.save(customDoctorGroup);

            SignFamily signFamily = signFamilyDao.findSsSignByDoctorPatient(sf.getDoctor(),sf.getPatient());

            if(signFamily != null){
                DoctorPatientGroupInfo ssDoctorGroup = new DoctorPatientGroupInfo();

                ssDoctorGroup.setCzrq(new Date());
                ssDoctorGroup.setDoctor(sf.getDoctor());
                ssDoctorGroup.setStatus(1);
                ssDoctorGroup.setPatient(p.getCode());
                ssDoctorGroup.setPname(p.getName());
                ssDoctorGroup.setPartAmount(0);
                ssDoctorGroup.setGroup(customGroup);
                ssDoctorGroup.setQyrq(new Date());
                ssDoctorGroup.setSignType("1");//三师签约

                doctorPatientGroupInfoDao.save(ssDoctorGroup);
            }
        }

        List<DoctorPatientGroupInfo> groups = doctorPatientGroupInfoDao.findPatientGroups(p.getCode());

        if (groups != null && groups.size() > 0) {
            for (DoctorPatientGroupInfo group : groups) {
                if(StringUtils.isNotEmpty(group.getSignType()) && group.getSignType().equals("2")) {
                    continue;
                }
                if(group.getGroup().equals(customGroup)){
                    continue;
                }

                DoctorPatientGroupInfo patientGroup = new DoctorPatientGroupInfo();

                patientGroup.setCzrq(new Date());
                patientGroup.setDoctor(group.getDoctor());
                patientGroup.setStatus(1);
                patientGroup.setPatient(p.getCode());
                patientGroup.setPname(p.getName());
                patientGroup.setPartAmount(0);
                patientGroup.setGroup(group.getGroup());
                patientGroup.setQyrq(new Date());
                patientGroup.setSignType("2");//家庭签约

                doctorPatientGroupInfoDao.save(patientGroup);
            }
        }

        if(!StringUtils.isEmpty(disease) && !disease.equals("0")){
            boolean flag =  patientDiseaseService.updatePatientDisease(sf.getPatient(),disease);

            if(!flag){
                throw new Exception("疾病更新失败");
            }
        }

        // 推送消息消息给微信端
        if (type == 1) {
            Doctor doc = doctorDao.findByCode(sf.getDoctor());
            Hospital hos = hospitalDao.findByCode(doc.getHospital());

            String content= "祝贺您，成功签约" + sf.getDoctorName() + "医生团队，您已可以享受家庭医生所带来的无微不至的健康保健服务。"+
                    "为了给您提供更好的服务，请尽快到" + (hos != null ? hos.getName() : "") + "社区（地址：" +
                    (hos != null ? hos.getAddress() : "") + "）缴费。";
            // 同意签约
            JSONObject json = new JSONObject();
            json.put("first", "签约成功通知");
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("date", DateUtil.dateToStrShort(sf.getBegin()));
            json.put("content", content);
            json.put("remark", "您好，您成功签约家庭医生");
            // 添加到发送队列
            PushMsgTask.getInstance().putWxMsg(access_token, 1, sf.getOpenid(), sf.getName(), json);
        } else if (type == 2) {
            System.out.println(" ---------- fail send weixin-------------");
            // 拒绝签约
            JSONObject json = new JSONObject();
            json.put("first", "签约失败通知");
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("date", DateUtil.dateToStrShort(sf.getBegin()));
            json.put("content", "您与 " + sf.getDoctorName() + " 医生建立家庭医生签约关系失败，请查看！");
            json.put("remark", "您好，签约家庭医生失败通知");
            // 添加到发送队列
            PushMsgTask.getInstance().putWxMsg(access_token, 2, sf.getOpenid(), sf.getName(), json);
        }
        return 1;
    }

    /**
     * 处理解约申请
     *
     * @param patient 患者标识
     * @param type    处理类型：1同意，2拒绝
     * @param reason  解约原因
     * @return
     */
    public int handleSurrender(String access_token, long msgid, String patient, int type, String reason) {
        if (type != 1 && type != 2) {
            return -1;
        }
        SignFamily sf = signFamilyDao.findByPatientCodeStatus(patient, 2);
        if (sf == null) {
            return 0;
        }
        // 更新消息状态为已处理
        if (msgid > 0) {
            Message message = messageDao.findOne(msgid);
            message.setRead(0);
            message.setOver("0");
        }
        if (type == 1) {
            // 将签约状态改为已解约
            sf.setReason(reason);
            sf.setStatus(-3);
            sf.setApplyUnsignDate(new Date());
            //signFamilyDao.handleSurrender(reason, patient);
            //设置患者所在团队失效
            doctorTeamDao.deleteTeam(sf.getTeamCode());
            //设置团队成员失效
            doctorTeamDoctor.deleteMember(sf.getTeamCode());
            //把患者移除健康管理师和全科医生的晃患者管理
            doctorPatientGroupInfoDao.deleteByPatient(patient);
            //结束患者家庭签约咨询
            consultTeamDao.updateStatusByPatient(patient);
            // 设置家庭签约疾病无效
            patientDiseaseService.updatePatientDisease(patient,"");

            // 推送消息消息给微信端
            JSONObject json = new JSONObject();
            json.put("first", "解约申请通知");
            json.put("date", DateUtil.getStringDateShort());
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("orgName", sf.getHospitalName());
            json.put("remark", "您好，您的签约医生已同意您的解约申请，解约已生效。");
            // 添加到发送队列
            PushMsgTask.getInstance().putWxMsg(access_token, 5, sf.getOpenid(), sf.getName(), json);
        } else {
            // 更新状态为正常
            signFamilyDao.refuseSurrender(patient);
            // 拒绝解约,推送消息消息给微信端
            JSONObject json = new JSONObject();
            json.put("first", "解约申请通知");
            json.put("date", DateUtil.getStringDateShort());
            json.put("doctor", sf.getDoctor());
            json.put("doctorName", sf.getDoctorName());
            json.put("orgName", sf.getHospitalName());
            json.put("remark", "您好，您的签约医生拒绝您的解约申请，解约失败。");
            // 添加到发送队列
            PushMsgTask.getInstance().putWxMsg(access_token, 5, sf.getOpenid(), sf.getName(), json);
        }
        return 1;
    }

    /**
     * 查询医生的签约消息
     *
     * @param doctor   医生标识
     * @param id
     * @param pagesize 分页大小
     * @return
     */
    public Page<Message> findMessageByDoctor(String doctor, long id, int pagesize) {
        if (pagesize <= 0) {
            pagesize = 10;
        }
        // 排序
        Sort sort = new Sort(Direction.DESC, "id");
        // 分页信息
        PageRequest pageRequest = new PageRequest(0, pagesize, sort);
        // 设置查询条件
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        filters.put("receiver", new SearchFilter("receiver", Operator.EQ, doctor));
        if (id > 0) {
            filters.put("id", new SearchFilter("id", Operator.LT, id));
        }
        // 只查询未处理的消息
        filters.put("type", new SearchFilter("type", Operator.EQ, 1));
        filters.put("over", new SearchFilter("over", Operator.EQ, 1));
        filters.put("read", new SearchFilter("read", Operator.EQ, 1));
        Specification<Message> spec = DynamicSpecifications.bySearchFilter(filters.values(), Message.class);
        return messageDao.findAll(spec, pageRequest);
    }

    /**
     * 查询已签约总数
     *
     * @param doctor
     * @return
     */
    public int countAmountSigned(String doctor) {
        return signFamilyDao.countAmountSignedByDoctor(doctor);
    }

    /**
     * 查询待签约总数
     *
     * @param doctor
     * @return
     */
    public int countAmountUnsign(String doctor) {
        return signFamilyDao.countAmountUnsignByDoctor(doctor);
    }

    public List<?> amountPatients(String uid) {
        return null;
    }

    public SignFamily getFamilyContractByIdcard(String idCard) {
        return signFamilyDao.findByIdcard(idCard);

    }

    public SignFamily getFamilyContractByMobile(String mobile) {
        return signFamilyDao.findByMobile(mobile);
    }

    /**
     * 生成签约标识
     *
     * @param doctor 医生标识
     * @return
     */
    private String createSignCode(String doctor, String hospital) {
        // 获取当前年份
        String year = DateUtil.getStringDate(DateUtil.YY);
        Hospital hospital1 = hospitalDao.findByCode(hospital);
        Integer amount=0;
        WlyySignFamilyCode wlyySignFamilyCode = wlyySignFamilyCodeDao.findByOrgCode(hospital);
        if(wlyySignFamilyCode!=null){
            amount=wlyySignFamilyCode.getSequence()+1;
            wlyySignFamilyCode.setSequence(amount);
            wlyySignFamilyCode.setModifyTime(new Date());
        }else{
            //创建序列
            amount=1;
            WlyySignFamilyCode wlyySignFamilyCodeTemp=new WlyySignFamilyCode();
            wlyySignFamilyCodeTemp.setModifyTime(new Date());
            wlyySignFamilyCodeTemp.setOrgCode(hospital1.getCode());
            wlyySignFamilyCodeTemp.setOrgName(hospital1.getName());
            wlyySignFamilyCodeTemp.setSequence(1);
            wlyySignFamilyCodeDao.save(wlyySignFamilyCodeTemp);
        }
        return year + hospital1.getRoadCode() + hospital1.getCenterSite() + StringUtils.leftPad(String.valueOf(amount + 1), 6, "0");
    }

    public int countAmountSigned2(String uid) {

        return signFamilyDao.countAmountSignedByHeather(uid);
    }

    public SignFamily findBySanshiPatient(String code) {

        return signFamilyDao.findSanshiSignByPatient(code);
    }
    public SignFamily findByJiatingPatient(String code) {

        return signFamilyDao.findFamilySignByPatient(code);
    }

    /**
     * 查询患者已签约信息
     *
     * @param code
     * @return
     */
    public SignFamily findBySsPatient(String code) {
        return signFamilyDao.findBySsPatient(code);
    }

    public List<Map<String, Object>> getDoctorsByhospitalNoPage(String hospital, String name, Integer type) {
        String sql = "select * from wlyy_doctor where 1=1 and del=1 and iscertified=1 and status=1 ";
        List<Object> params = new ArrayList<Object>();
        if (StringUtils.isNoneEmpty(hospital)) {
            sql += " and hospital =? ";
            params.add(hospital);
        }
        if (StringUtils.isNoneEmpty(name)) {
            sql += " and name like ? ";
            params.add("%" + name + "%");
        }
        if (type != null && type > 0) {
            sql += " and level =? ";
            params.add(type);
        }
        return jdbcTemplate.queryForList(sql, params.toArray());
    }

    public Map<String, Object> getSanshiSignByPatientCode(String patientCode) {
        Map<String, Object> map = new HashMap<>();
        SignFamily signFamily = signFamilyDao.findBySanshiPatient(patientCode);
        //判斷之前有没有三师签约
        if (signFamily != null) {
            map.put("hasSanshi", "true");
            //得到团队的专科医生
            DrHealthTeamMember drHealthTeamMember = doctorTeamDoctor.findSanshiByTeamAndType(signFamily.getTeamCode(), 1);
            map.put("zkCode", drHealthTeamMember.getMemberCode());
            map.put("zkName", drHealthTeamMember.getName());
            //得到团队的全科医生
            drHealthTeamMember = doctorTeamDoctor.findSanshiByTeamAndType(signFamily.getTeamCode(), 2);
            map.put("qkCode", drHealthTeamMember.getMemberCode());
            map.put("qkName", drHealthTeamMember.getName());
            //得到团队的健康管理医生
            drHealthTeamMember = doctorTeamDoctor.findSanshiByTeamAndType(signFamily.getTeamCode(), 3);
            map.put("glsCode", drHealthTeamMember.getMemberCode());
            map.put("glsName", drHealthTeamMember.getName());
            //得到之前病人得的病
            Patient pa = patientDao.findByCode(patientCode);
            map.put("disease", pa.getDisease());
        } else {
            map.put("hasSanshi", "false");
        }
        return map;
    }

    public SignFamily findByPatientYes(String id) {
        return signFamilyDao.findByjiatingPatient(id);
    }

    public SignFamily findBySanshiPatientYes(String id) {
        return signFamilyDao.findBySanshiPatientYes(id);
    }

    /**
     * 根据身份证号查找病人的三师签约信息
     *
     * @param idCard
     * @return
     */
    public JSONObject getSanshiSingInfoByPatientIdCard(String idCard) throws Exception {
        JSONObject result = new JSONObject();
        SignFamily sign = signFamilyDao.findByPatientSanshiSignInfo(idCard);
        SignFamily signFamily = signFamilyDao.findByPatientFamilySignInfo(idCard);

        Patient p = patientDao.findByIdcard(idCard);

        if (p == null) {
            result.put("signStatus", "0");
            result.put("msg", "病人未注册");
            return result;
        }
        if (signFamily != null) {
            result.put("signStatus", "2");
            result.put("msg", "病人已申请过家庭签约!");
            return result;
        }

        if (sign != null) {
            List<DrHealthTeamMember> members = doctorTeamDoctor.findByTeamAndDel(sign.getTeamCode(), "1");

            if (members == null) {
                throw new Exception("签约团队信息有误!");
            }

            //三师签约医生信息
            for (DrHealthTeamMember member : members) {
                if (member.getType() == 1) {
                    result.put("majorDoctor", member.getMemberCode());
                    result.put("majorDoctorName", member.getName());
                } else if (member.getType() == 2) {
                    Doctor doctor=doctorDao.findByCode(member.getMemberCode());
                    result.put("hospital",doctor.getHospital());
                    result.put("doctor", member.getMemberCode());
                    result.put("doctorName", member.getName());
                } else if (member.getType() == 3) {
                    result.put("healthDoctor", member.getMemberCode());
                    result.put("healthDoctorName", member.getName());
                }
            }

            // 查询患者疾病
            String diseases = redisTemplate.opsForValue().get("disease:" + p.getCode());
            if(!StringUtils.isEmpty(diseases)){
                JSONArray array = new JSONArray(diseases);
                JSONArray disArray = new JSONArray();

                for(int i = 0; i < array.length(); i++){
                    JSONObject json = array.getJSONObject(i);
                    if(json != null && json.get("signType").toString().equals("1")){
                        disArray.put(json);
                    }
                }

                result.put("diseases",disArray);
            }else{
                result.put("diseases","");
            }


            result.put("signStatus", "1");

        } else {
            result.put("signStatus", "3");
        }

        if(p != null){
            JSONObject pJson = new JSONObject(p);
            result.put("patient",pJson);
        }

        return result;
    }

    public JSONArray getSignDoctorMessage(String patientCode) {
        JSONArray jsonArray = new JSONArray();
        //找出患者的三师签约信息
        SignFamily signFamily = signFamilyDao.findSanshiSignByPatient(patientCode);
        Patient patient=patientDao.findByCode(patientCode);
        if (signFamily != null) {
            //得到三师签约的服务团队
            List<Doctor> doctors = doctorDao.findSanshiDoctorByTeam(signFamily.getTeamCode());
            for (Doctor doctor : doctors) {
                JSONObject jo = new JSONObject();
                jo.put("code", doctor.getCode());//医生code
                jo.put("sex", doctor.getSex());//医生性别  1男，2女）
                jo.put("name", doctor.getName());//医生名称
                jo.put("photo", doctor.getPhoto());//医生头像
                jo.put("hosptialName", doctor.getHosptialName());//所属机构名称
                jo.put("level", doctor.getLevel());//医生等级1专科医生，2全科医生，3健康管理师
                jo.put("signType", "1");//签约类别 1是三师 2是家庭
                jo.put("signStatus", signFamily.getStatus());//签约状态 0待签约，1已签约 2待解约
                jo.put("jobName", doctor.getJobName());//职称
                jo.put("disease", patient.getDisease());//0健康，1高血压，2糖尿病，3高血压+糖尿病
                if(signFamily.getStatus()==0){
                    jo.put("sqDate", DateUtil.dateToStrShort(signFamily.getPatientApplyDate()));//申请时间
                }else if(signFamily.getStatus()==1){
                    jo.put("qyDate", DateUtil.dateToStrShort( signFamily.getApplyDate()));//签约时间
                    jo.put("endDate", DateUtil.dateToStrShort( signFamily.getEnd()));//结束时间
                }else if(signFamily.getStatus()==2){
                    jo.put("qyDate", DateUtil.dateToStrShort( signFamily.getPatientApplyUnsignDate()));//申请解约时间
                    jo.put("endDate", DateUtil.dateToStrShort( signFamily.getEnd()));//结束时间
                }
                jsonArray.put(jo);
            }
        }
        //得到家庭签约
        SignFamily jtSignFamily = signFamilyDao.findFamilySignByPatient(patientCode);

        if (jtSignFamily != null) {
            //家庭签约只找全科医生
            Doctor doctor = doctorDao.findByCode(jtSignFamily.getDoctor());
            if(doctor !=null){
	            JSONObject jo = new JSONObject();
	            jo.put("code", doctor.getCode());
	            jo.put("sex", doctor.getSex());
	            jo.put("name", doctor.getName());
	            jo.put("photo", doctor.getPhoto());
	            jo.put("hosptialName", doctor.getHosptialName());
	            jo.put("level", doctor.getLevel());
	            jo.put("signType", "2");//三师签约
	            jo.put("signStatus", jtSignFamily.getStatus());
	            jo.put("jobName", doctor.getJobName());
	            jo.put("disease", patient.getDisease());//0健康，1高血压，2糖尿病，3高血压+糖尿病
	            if(jtSignFamily.getStatus()==0){
	                jo.put("sqDate", DateUtil.dateToStrShort(jtSignFamily.getPatientApplyDate()));//申请时间
	            }else{
	                jo.put("qyDate", DateUtil.dateToStrShort( jtSignFamily.getApplyDate()));//签约时间
	                jo.put("endDate", DateUtil.dateToStrShort( jtSignFamily.getEnd()));//结束时间
	            }
	            jsonArray.put(jo);
            }
        }
        return jsonArray;
    }

    public SignFamily getPatientSign(String patient) {
        return signFamilyDao.findByPatient(patient);
    }

    public SignFamily getssPatientSign(String invitePatientCode) {
        return signFamilyDao.findBySsPatient(invitePatientCode);
    }


    /**
     * 患者家庭签约收费类型更新
     *
     * @param expensesType
     * @param patient
     * @return
     */
    public boolean updateExpensesType(String expensesType,String patient) {
        if (signFamilyDao.updateExpensesType(expensesType, patient) > 0) {
            return true;
        }else{
            return false;
        }
    }
}
